<template>
  <CustomDialog ref="customDialog" width="600px" :title="dialogProps.title" :isView="dialogProps.isView"
    :onSubmit="handleSubmit" :onClose="handleClose">
    <template #header>
      {{ `${dialogProps.title}菜单` }}
    </template>
    <template #content>
      <el-form ref="ruleFormRef" label-width="120px" label-suffix=" :" :rules="rules" :disabled="dialogProps.isView"
        :model="dialogProps.row" :hide-required-asterisk="dialogProps.isView">
        <el-form-item label="菜单类型" prop="menuType">
          <el-select v-model="dialogProps.row!.menuType" placeholder="请选择菜单类型" clearable @change="handleMenuType">
            <el-option label="目录" value="M"></el-option>
            <el-option label="菜单" value="C"></el-option>
            <el-option label="按钮" value="F"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="缓存标识" prop="cacheCode">
          <el-input v-model="dialogProps.row!.cacheCode" placeholder="请输入缓存标识" clearable />
        </el-form-item>
        <el-form-item label="菜单图标" prop="icon">
          <SelectIcon v-model:icon-value="dialogProps.row!.icon" />
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName" placeholder="请输入菜单名称" clearable>
          <el-input v-model="dialogProps.row!.menuName" />
        </el-form-item>
        <el-form-item label="路径地址" prop="url" v-if="dialogProps.row.menuType !== 'F'">
          <el-input v-model="dialogProps.row!.url" />
        </el-form-item>
        <el-form-item label="菜单排序" prop="orderNum">
          <el-input-number v-model="dialogProps.row!.orderNum" controls-position="right" />
        </el-form-item>
        <el-form-item label="权限标识" prop="perms"
          :rules="[{ required: dialogProps.row.menuType == 'F', message: '权限标识不能为空' }]">
          <el-input v-model="dialogProps.row!.perms" />
        </el-form-item>
        <el-form-item label="菜单隐藏" prop="visible">
          <el-radio-group v-model="dialogProps.row.visible">
            <el-radio-button label="否" value="0" />
            <el-radio-button label="是" value="1" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单缓存" prop="cache">
          <el-radio-group v-model="dialogProps.row.cache">
            <el-radio-button label="否" value="0" />
            <el-radio-button label="是" value="1" />
          </el-radio-group>
        </el-form-item>
        <!-- 是否存在数据权限 0 没有数据权限 1 有数据权限 -->
        <el-form-item label="数据权限" prop="dataPermission">
          <el-radio-group v-model="dialogProps.row.dataPermission">
            <el-radio-button label="否" value="0" />
            <el-radio-button label="是" value="1" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上级菜单" prop="parentId" v-if="dialogProps.row.menuType !== 'M'">
          <el-tree-select v-model="dialogProps.row.parentId" :data="dialogProps.allData" filterable check-strictly />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="customDialog?.acceptParams(false)">取消</el-button>
      <el-button v-show="!dialogProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </CustomDialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import CustomDialog from "@/components/Dialog/CustomDialog.vue";
import BInput from "@/components/BaseComponents/BInput.vue";
import SelectIcon from "@/components/SelectIcon/index.vue";

const rules = reactive({
  menuType: [{ required: true, message: "菜单类型必选" }],
  menuName: [{ required: true, message: "菜单名称必填" }],
  cacheCode: [{ required: true, message: "缓存标识为菜单名称的英文" }],
  url: [{ required: true, message: "路径地址必填" }],
  visible: [{ required: true, message: "菜单隐藏必填" }],
  cache: [{ required: true, message: "菜单缓存必填" }],
  dataPermission: [{ required: true, message: "数据权限必填" }],
  parentId: [{ required: true, message: "上级菜单必选" }],
});

interface DialogProps {
  title: string;
  isView: boolean;
  row: any;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  allData?: any
}

const dialogProps = ref<DialogProps>({
  isView: false,
  title: "",
  row: {},
  allData: []
});

const customDialog = ref<InstanceType<typeof CustomDialog>>();
//转换为树形结构
const convertToTreeSelectData = (data: any): any[] => {
  return data.map(node => {
    const treeSelectNode: any = {
      value: node.id,
      label: node.menuName,
      children: node.children ? convertToTreeSelectData(node.children) : undefined
    };
    return treeSelectNode;
  });
}

const handleMenuType = (type: string) => {
  if (type === 'F') {
    dialogProps.value.row.url = '';
    dialogProps.value.row.perms = 'button';
  }
}

// 接收父组件传过来的参数
const acceptParams = async (params: DialogProps) => {
  console.log(params);

  //修改，使新增时数据不清除
  dialogProps.value.api = params.api;
  dialogProps.value.getTableList = params.getTableList;
  dialogProps.value.title = params.title;
  dialogProps.value.isView = params.isView;
  dialogProps.value.allData = convertToTreeSelectData(params.allData);
  dialogProps.value.row = params.row;
  dialogProps.value.row.cache = params.row.cache ? params.row.cache : '0';
  dialogProps.value.row.visible = params.row.visible ? params.row.visible : '0';
  dialogProps.value.row.dataPermission = params.row.dataPermission ? params.row.dataPermission : '0';

  customDialog.value?.acceptParams(true);
};


// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      dialogProps.value.row.parentId = dialogProps.value.row.parentId ? dialogProps.value.row.parentId : 0;
      await dialogProps.value.api!(dialogProps.value.row);
      ElMessage.success({ message: `${dialogProps.value.title}菜单成功！` });
      customDialog.value?.acceptParams(false);
      dialogProps.value.getTableList!();
    } catch (error) {
      console.log(error);
    }
  });
};

const handleClose = () => {
  customDialog.value?.acceptParams(false);
};

defineExpose({
  acceptParams
});
</script>
